package com.da.javatest.leetCode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author chenlida
 * @date 2019/1/18 11:37
 * @description
 */
public class Code445 {
    public static void main(String[] args) {
        char[] chars = {'7', '8', '0', '7'};
        Code445 code445 = new Code445();
        ListNode k = new ListNode(Integer.parseInt(chars[0] + ""));
        code445.setNode(k, 1, chars);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        setNum(l1, list1);
        setNum(l2, list2);
        Collections.reverse(list1);
        Collections.reverse(list2);
        char[] chars = getResultChars(list1, list2);
        ListNode l = new ListNode(Integer.parseInt(chars[0] + ""));
        setNode(l, 1, chars);
        return l;
    }

    private char[] getResultChars(List<Integer> l1, List<Integer> l2) {
        StringBuilder sb = new StringBuilder();
        boolean flag = false;
        int max = Math.max(l1.size(), l2.size());
        for (int i = 0; i < max; i++) {
            int r1 = l1.size() > i ? l1.get(i) : 0;
            int r2 = l2.size() > i ? l2.get(i) : 0;
            int r = r1 + r2;
            if (flag) {
                r++;
                flag = false;
            }
            if (r > 9) {
                flag = true;
                r -= 10;
            }
            sb.append(r);
        }
        if (flag) {
            sb.append(1);
        }
        return sb.reverse().toString().toCharArray();
    }

    private void setNum(ListNode l, List<Integer> list) {
        if (l != null) {
            list.add(l.val);
            setNum(l.next, list);
        }

    }

    private void setNode(ListNode l, int index, char[] chars) {
        if (index < chars.length) {
            l.next = new ListNode(Integer.parseInt(chars[index] + ""));
            setNode(l.next, index += 1, chars);
        }
    }
}
